package ua.kharkov.photo.bl;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageThumbnailCreator {
	public static byte[] createThumbnail(byte[] imageData, int size,
			String format) throws IOException {
		BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));
		if (image == null)
			return null;

		Image thumbnail;
		if (image.getWidth() > image.getHeight())
			thumbnail = image.getScaledInstance(size, -1, Image.SCALE_SMOOTH);
		else
			thumbnail = image.getScaledInstance(-1, size, Image.SCALE_SMOOTH);

		image = new BufferedImage(thumbnail.getWidth(null),
				thumbnail.getHeight(null), BufferedImage.TYPE_INT_RGB);

		image.getGraphics().drawImage(thumbnail, 0, 0, null);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(image, format, baos);
		return baos.toByteArray();
	}

	public static ByteArrayInputStream getInputThumbnailStream(
			ByteArrayInputStream inputStreamLarge) throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();

		int nRead;
		byte[] data = new byte[16384];

		while ((nRead = inputStreamLarge.read(data, 0, data.length)) != -1) {
			buffer.write(data, 0, nRead);
		}
		buffer.flush();

		return new ByteArrayInputStream(createThumbnail(buffer.toByteArray(),
				100, "jpg"));
	}
}
